package cn.cosmosx.controller.calc;

import cn.cosmosx.base.calc.Loan;
import cn.cosmosx.base.calc.LoanCalculator;
import cn.cosmosx.base.calc.Param;
import cn.cosmosx.base.define.PageQuery;
import cn.cosmosx.base.define.ResultVO;
import cn.cosmosx.base.util.TransferVoUtils;
import cn.cosmosx.controller.calc.param.CalcParam;
import cn.cosmosx.controller.calc.vo.LoanVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

@Api(tags = "还款计划试算")
@Slf4j
@RestController
@RequestMapping(value = "/calc")
public class LoanController {

    @ApiOperation(value = "等额本金")
    @PostMapping("/eq/Capital")
    public ResultVO<IPage<LoanVO>> eqCapital(@Validated @RequestBody PageQuery<CalcParam> param) {
        Map<Integer, Loan> loanMap = LoanCalculator.calcEqCapital(TransferVoUtils.transferVO(param.getQueryParam(), Param.class));
        return ResultVO.success(pageHandle(loanMap.values(), param.getCurrent(), param.getSize()));
    }

    @ApiOperation(value = "等额本息")
    @PostMapping("/eq/capitalAndInterest")
    public ResultVO<IPage<LoanVO>> eqCapitalAndInterest(@Validated @RequestBody PageQuery<CalcParam> param) {
        Map<Integer, Loan> loanMap = LoanCalculator.calcEqCapitalAndInterest(TransferVoUtils.transferVO(param.getQueryParam(), Param.class));
        return ResultVO.success(pageHandle(loanMap.values(), param.getCurrent(), param.getSize()));
    }

    private IPage<LoanVO> pageHandle(Collection<Loan> data, long currentIndex, long size) {
        IPage<LoanVO> page = Page.of(currentIndex, size, data.size());
        int startIndex = (int) ((page.getCurrent() - 1) * page.getSize());
        if (startIndex > page.getTotal()) {
            startIndex = (int) (page.getTotal() - 1);
        }
        int endIndex = (int) (startIndex + page.getSize());
        if (endIndex > page.getTotal()) {
            endIndex = (int) page.getTotal();
        }
        page.setRecords(TransferVoUtils.transferVOs(new ArrayList<>(data).subList(startIndex, endIndex), LoanVO.class));
        return page;
    }

}
